<?php

namespace app\index\controller;

use app\BaseController;
use Exception;
use frame\lib\Captcha;
use frame\lib\Db;
use frame\lib\VerfiyParam;

require ROOT_PATH . 'vendor/autoload.php';

use PHPMailer\PHPMailer\PHPMailer;

class Register extends BaseController
{
    public function index()
    {
        return $this->view('index');
    }
    public function captcha()
    {
        return new Captcha();
    }
    // 一级用户注册入口
    public function doReg()
    {
        $conf = config('system', 'switch');
        if ($conf['is_reg'] == 0) error('网页禁止注册，请联系管理员 !');
        $ip = ip();
        $sql = "select max(id) as id from user where ip = '{$ip}';";
        $limitReg = Db::query($sql);
        if (@$limitReg['id']) {
            $limitReg =  Db::name('user')->where(['id' => $limitReg['id']])->find();
            if (date('d', getTime(3, $limitReg['create_time'])) == date('d', time())) error('一个IP每天只能注册一个账户哦 !');
        }
        $param = $_POST;
        $rule = [
            'username|用户名' => 'require|min:6|max:12|alphaNum',
            'password|密码' => 'require|min:6|max:12|alphaNum',
            'code|验证码' => 'require|min:4',
            'email|邮箱' => 'require|email'
        ];
        VerfiyParam::init($param, $rule);
        // if (!captcha_check($param['code'])) error('验证码错误', 203);
        // 验证码
        $this->verifyCode($param['code']);
        $user = Db::name('user')->where(['username' => $param['username'], 'role' => 1])->find();
        if ($user) error('用户名已存在，请更换另一个吧!');
        $data = [
            'username' => $param['username'],
            'password' => encrypt_pwd($param['password']),
            'email' => $param['email'],
            'role' => 1,
            'status' => 1,
            'ip' => ip(),
            'create_time' => getTime(),
            'vip_time' => getTime(2, config('system', 'other')['reg_vip_time'] + time())
        ];
        $res = Db::name('user')->insert($data);
        if ($res) {
            $userData = Db::name('user')->where(['role' => 1, 'username' => $param['username']])->find();
            $this->apiInit($userData['id']);
            $this->userLimitInit($userData['id']);
            success();
        }
        error();
    }
    // 初始化 接口配置
    public function apiInit($uid = '')
    {
        $hasExist = Db::name('config')->where(['user_id' => $uid])->find();
        if (!$hasExist) {
            $data = [
                'new' => '还未设置公告哦 !',
                'new_switch' => '1',
                'update_new' => '更新内容还未设置',
                'feedback' => 1,
                'is_log' => 1,
                'is_sign' => 1,
                'version' => '1',
                'log_send_score' => 0,
                'reg_send_score' => 0,
                'reg_vip_time' => 0,
                'downloadLink' => '',
                'sign_three' => 5,
                'sign_seven' => 10,
                'sign_fifteen' => 15
            ];
            $data = json_encode($data, JSON_UNESCAPED_UNICODE);
            $res = Db::name('config')->insert(['user_id' => $uid, 'conf' => $data]);
            if (!$res) error('接口配置初始化失败，请重新登录 !');
        }
    }
    public function userLimitInit($uid = '')
    {

        $res =  Db::name('user_limit')->where(['uid' => $uid])->find();
        if (!$res) {
            $data = ['uid' => $uid];
            Db::name('user_limit')->insert($data);
        }
    }
    public function getCode()
    {
        if (@$_SESSION['code_expire'] > time()) {
            error('验证码有效期为5分钟，请稍后再来测试');
        }
        $email = $_POST['email'];
        // 生成6位随机验证码
        $verificationCode = str_pad(mt_rand(0, 999999), 6, '0', STR_PAD_LEFT);
        $_SESSION['reg_code'] = $verificationCode;
        $_SESSION['code_expire'] = time() + 300;
        $mail = new PHPMailer(true);
        $conf = config('email');
        
        try {
            // SMTP服务器配置
            $mail->isSMTP();
            $mail->Host       = $conf['Host'];
            $mail->SMTPAuth   = true;
            $mail->Username   = $conf['Username'];
            $mail->Password   = $conf['Password'];
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
            $mail->Port       = 465;
            // 收发件人配置
            $mail->setFrom($conf['Username'], '后台注册');
            $mail->addAddress($email);
            $mail->isHTML(false);
            $mail->Subject = '您的注册验证码';
            $mail->Body    = "您的注册验证码是：{$verificationCode}\n"
                . "该验证码5分钟内有效，请尽快完成注册。";

            $mail->send();
            success();
        } catch (Exception $e) {
            unset($_SESSION['code_expire']);
            error("发送失败，请重试。错误信息：" . $mail->ErrorInfo);
        }
    }
    public function verifyCode($code)
    {
        if (@$_SESSION['reg_code'] != $code) {
            error('验证码错误');
        }
        if (@$_SESSION['code_expire'] < time()) {
            error('验证码已过期');
        }
    }
}
